package com.igeek.ch02.dao;

import com.igeek.ch02.entity.User;
import com.igeek.ch02.utils.JDBCUtils;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;

/**
 * @Description 用户的数据交互层
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/1/5 16:56
 */
public class UserDao extends BaseDao<User> {

    //根据姓名和密码，查询用户信息
    public User selectOne(String name,String pwd) throws SQLException {
        String sql = "select * from user where name = ? and pwd = ?";
        User user = this.getBean(JDBCUtils.getConn(), sql, User.class, name, pwd);
        return user;
    }

    //插入用户信息
    public int insert(User user) throws SQLException {
        String sql = "insert into user values(null,?,?,?,?,?,?,0)";
        Calendar c = Calendar.getInstance();
        c.setTime(user.getBirthday());
        int age = LocalDate.now().getYear() - c.get(Calendar.YEAR);
        int i = this.update(JDBCUtils.getConn() , sql , user.getName() ,age+1 ,
                user.getGender() , user.getBirthday() , user.getPic(),
                user.getPwd());
        return i;
    }

    //查看用户列表的总记录数
    public int selectCounts() throws SQLException {
        String sql="select count(*)from user ";
        Long value=(Long) this.getSingleValue(JDBCUtils.getConn(),sql);
        return value.intValue();
    }

    //查看用户列表数据
    public List<User> selectAll(int begin) throws SQLException {
        String sql="select * from user limit ?, 3 ";
        List<User> userList=this.getBeanList(JDBCUtils.getConn(),sql,User.class,begin);
        return userList;
    }

    //根据id删除用户信息
    public int delete(int id) throws SQLException {
        String sql="delete from user where id=?";
        int i = this.update(JDBCUtils.getConn(), sql, id);
        return i;
    }

    //根据user对象更新用户信息
    public int update(User user) throws SQLException {
        String sql="update user set name=?,gender=?,birthday=?,age=?,pic=? where id=?";
        Calendar c=Calendar.getInstance();
        c.setTime(user.getBirthday());
        int age=LocalDate.now().getYear()-c.get(Calendar.YEAR);
        int i=this.update(JDBCUtils.getConn(),sql,user.getName(),user.getGender(),
                user.getBirthday(),age+1,user.getPic(),user.getId());
        return i;
    }

    //根据id查询用户
    public User selectOne(int id) throws SQLException {
        String sql="select * from user where id = ?";
        User user=this.getBean(JDBCUtils.getConn(),sql,User.class,id);
        return user;
    }

}
